package com.nanfang51g3.ckz.ui.person;

import android.graphics.BitmapFactory;

import com.nanfang51g3.ckz.di.ApiModule;
import com.nanfang51g3.ckz.domain.HttpResultBean;
import com.nanfang51g3.ckz.domain.SuccessBean;
import com.nanfang51g3.ckz.domain.UserBean;
import com.nanfang51g3.ckz.exec.Api2Exception;
import com.nanfang51g3.ckz.http.HttpResultFunc;
import com.nanfang51g3.ckz.http.RestApi;
import com.nanfang51g3.ckz.http.SubscriberInterface;
import com.nanfang51g3.ckz.ui.base.BasePresenter;
import com.nanfang51g3.ckz.utils.KLog;
import com.nanfang51g3.ckz.utils.MD5Utils;
import com.nanfang51g3.ckz.utils.SPUtil;

import java.io.File;
import java.util.Collections;
import java.util.TreeMap;

import javax.inject.Inject;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016/4/13.
 */
public class PersonPresenter extends BasePresenter implements PersonContract.PersonActionsListener {
    String message;
    private final RestApi _restApi;
    private final PersonContract.View mView;

    @Inject
    public PersonPresenter(RestApi restApi, PersonContract.View mView) {
        KLog.i("TAG", "进入了...PersonPresenter");
        /**
         * @see ApiModule#provideRestApi(Retrofit)
         */
        this._restApi = restApi;
        KLog.i("TAG", _restApi == null ? "进入了...is null" : "进入了...not null");
        /**
         * @see PersonPresenterModule#PersonPresenterModule(PersonContract.View)
         */
        this.mView = mView;
        KLog.i("TAG", mView == null ? "进入了...is null" : "进入了...not null");
    }

    @Override
    public void requestUserInfo() {
        TreeMap<String, String> treeMap = new TreeMap<>();
        String userid = (String) SPUtil.get(mView.getContext(), "userid", "");
        treeMap.put("userid", userid);
        KLog.i("Evd", "requestUserInfo=" + userid);
        String sign = MD5Utils.getAccessToken(treeMap);
        Observable    observable = _restApi.userinfo(userid, sign);
        Subscription subscription =  observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())

                .map(new PersonResultFunc<UserBean>())
                .subscribe(new SubscriberInterface<UserBean>() {
                    @Override
                    public void onCompleted() {
                        KLog.i("Evd", "onCompleted ");
                    }

                    @Override
                    public void _onError(String msg) {
                        KLog.i("Evd", "onError " + msg);
                        /**
                         * @see  PersonActivity#showMessage(String)
                         */
                        mView.showMessage(msg);
                    }

                    @Override
                    public void onNext(UserBean o) {
                        KLog.i("Evd", "onNext " + o.toString());
                        String userPic = o.getUserpic().equals("") ? "" : "";
                        String userNmae = o.getUsername().equals("") ? "暂未填写" : o.getUsername();
                        String email = o.getEmail().equals("") ? "暂未填写" : o.getEmail();
                        String qq = o.getQq().equals("") ? "暂未填写" : o.getQq();
                        String phone = o.getPhone().equals("") ? "暂未填写" : o.getPhone();
                        /**
                         * @see  PersonActivity#showUi(String, String, String, String, String)
                         */
                        mView.showUi(userPic, userNmae, email, qq, phone);
                    }
                });
        addSubscrebe(subscription);
    }


    private BitmapFactory.Options getBitmapOption(int inSampleSize) {

        System.gc();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPurgeable = true;
        options.inSampleSize = inSampleSize;
        return options;
    }

    @Override
    public void updateAvatar(final File file) {
        String userid = (String) SPUtil.get(mView.getContext(), "userid", "");
        try {
//            InputStream in = new FileInputStream(new File(file.getPath()));
//            byte[] buf;
//            buf = new byte[in.available()];
//            while (in.read(buf) != -1) ;
//            KLog.i("Evd", buf == null ? "buf = 0" : "buf = " + buf.length);
//            RequestBody requestBody = RequestBody
//                    .create(MediaType.parse("application/octet-stream"), buf);
//            KLog.i("Evd", buf == null ? "buf = 0" : "buf = " + buf.toString());
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
            Observable<HttpResultBean<SuccessBean>> observable = _restApi.userpic(Collections.singletonMap("userid", userid), requestBody);
            observable
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .map(new PersonResultFunc<SuccessBean>())
                    .subscribe(new SubscriberInterface<SuccessBean>() {
                        @Override
                        public void onCompleted() {
                            KLog.i("Evd", "onCompleted -  ");
                        }

                        @Override
                        public void _onError(String msg) {
                            KLog.i("Evd", "onError " + msg);
                            /**
                             * @see  PersonActivity#showMessage(String)
                             */
                            mView.showMessage(msg);
                        }

                        @Override
                        public void onNext(SuccessBean o) {
                            KLog.i("Evd", "onNext -  " + o.toString());
                            SPUtil.putAndApply(mView.getContext(), "is_avatar", true);
                            SPUtil.putAndApply(mView.getContext(), "userpic", o.getUserpic());
                            /**
                             * @see  PersonActivity#showMessage(String)
                             */
                            mView.showMessage(message);
                            mView.showAvatar(file);
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class PersonResultFunc<T> extends HttpResultFunc<T> {
        @Override
        public T call(HttpResultBean<T> httpResult) {
            KLog.i("Evd", httpResult == null ? "1-" : "0-" + httpResult.getCode() + "-" + httpResult.getInfo() + "-" + httpResult.getData().toString());
            if (httpResult.getCode() == 2) {
                throw new Api2Exception(httpResult.getInfo());
            }
            message = httpResult.getInfo();
            return httpResult.getData();
        }
    }

}
